package com.zengchen.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;


public class Base64Utils {

    /**
     * <p>
     *  BASE64字符串解码为二进制数据
     * </p>
     *
     * @param base64
     * @return
     * @throws Exception
     */
    public static byte[] decode(String base64) throws Exception {
        return Base64.getMimeDecoder().decode(base64);
    }

    /**
     * <p>
     *  二进制数据编码为BASE64字符串
     * </p>
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static String encode(byte[] bytes) throws Exception {
        return Base64.getMimeEncoder().encodeToString(bytes);
    }

    /**
     * <p>
     *  字符串按utf-8 转为byte[] 编码为BASE64字符串
     * </p>
     *
     * @param target 目标字符串
     * @return
     * @throws Exception
     */
    public static String encode(String target) throws Exception {
        return Base64.getMimeEncoder().encodeToString(target.getBytes("utf-8"));
    }

    /**
     * 将字符串进行压缩并转换成base64字符
     *
     * @param data （非空字符串）
     * @return 压缩将转换成base64的字符串
     */
    public static String zipBase64(String data) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(bos);
        gzip.write(data.getBytes());
        gzip.finish();
        return Base64.getEncoder().encodeToString(bos.toByteArray());
    }

    /**
     * 将字符串进行base64解码并进行解压
     *
     * @param data 被压缩并转换成base64的字符串(非空)
     * @return
     */
    public static String base64Unzip(String data) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(data));
        GZIPInputStream gzip = new GZIPInputStream(bis);
        byte[] buf = new byte[16384];
        int num = -1;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            while ((num = gzip.read(buf, 0, buf.length)) != -1) {
                bos.write(buf, 0, num);
            }
            bos.flush();
            return new String(bos.toByteArray());
        }
    }
}
